package com.onec.service.customer.service.impl;

import com.onec.service.api.enums.StatusEnum;
import com.onec.service.api.enums.error.AgentErrorEnum;
import com.onec.service.api.exception.CustomerException;
import com.onec.service.customer.dao.agent.AgentBusinessRepository;
import com.onec.service.customer.dao.agent.AgentInfoRepository;
import com.onec.service.customer.dao.agent.AgentKeyRepository;
import com.onec.service.customer.entity.agent.AgentBusiness;
import com.onec.service.customer.entity.agent.AgentInfo;
import com.onec.service.customer.entity.agent.AgentKey;
import com.onec.service.service.AgentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 机构信息查询服务类；
 *
 * @author onec
 */
@Service
public class AgentInfoServiceImpl implements AgentInfoService {

//    @Autowired
//    private LoginUserHolder loginUserHolder;

    @Autowired
    AgentInfoRepository agentInfoRepository;

    @Autowired
    AgentKeyRepository agentKeyRepository;

    @Autowired
    AgentBusinessRepository agentBusinessRepository;

    @Override
    public AgentInfo getAgentInfo(String agentCode) {
        //       loginUserHolder.getCurrentUser();
        return agentInfoRepository.findByAgentCode(agentCode);
    }

    /**
     * 获取机构信息
     *
     * @param
     * @return
     */
    @Override
    public AgentInfo getAvailableAgent(String agentCode) {
        AgentInfo agentInfo = getAgentInfo(agentCode);
        if (Optional.ofNullable(agentInfo).isEmpty()) {
            throw new CustomerException(AgentErrorEnum.INVALID);
        }

        if (!StatusEnum.isSuccess(agentInfo.getStatus())) {
            throw new CustomerException(AgentErrorEnum.FREEZE);
        }
        return agentInfo;
    }

    @Override
    public AgentKey getAgentKey(long agentId) {
        return agentKeyRepository.findAgentKeyByAgentId(agentId);
    }

    @Override
    public AgentBusiness getAgentBus(long agentId, String businessNo) {
        return agentBusinessRepository.findByAgentIdAndBusinessNo(agentId, businessNo);
    }

    @Override
    public AgentBusiness getAvailableAgentBus(long agentId, String businessNo) {
        AgentBusiness agentBusiness = getAgentBus(agentId, businessNo);
        if (Optional.ofNullable(agentBusiness).isEmpty()) {
            throw new CustomerException(AgentErrorEnum.INVALID_BUS);
        }

        if (!StatusEnum.isSuccess(agentBusiness.getStatus())) {
            throw new CustomerException(AgentErrorEnum.FREEZE_BUS);
        }
        return agentBusiness;
    }
}
